package com.yunqian.util.message;

import com.yunpian.sdk.model.ResultDO;
import com.yunpian.sdk.model.SendSingleSmsInfo;
import com.yunpian.sdk.service.SmsOperator;
import com.yunpian.sdk.service.YunpianRestClient;
import com.yunqian.constant.ConstantKey;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * Created by Home on 2016/7/2.
 */
public class YunpianSmsUtil {

    private static final Logger logger = LoggerFactory.getLogger(YunpianSmsUtil.class);

    private static YunpianRestClient client;

    static {
        try {
            client = new YunpianRestClient(ConstantKey.YUNPIAN_APIKEY);
            // yunpian sdk中的Config类有重置log4j配置 比较烂的sdk..，此处需要再改回来
            LogManager.resetConfiguration();
            Properties properties = new Properties();
            properties.load(Thread.currentThread().getContextClassLoader()
                                  .getResourceAsStream("log4j2-prod.xml"));
            PropertyConfigurator.configure(properties);
        } catch (Exception e) {
            logger.error("云片sdk初始化失败", e);
        }
    }

    /**
     * 发送短信
     *
     * @param templateTxt 短信模板标识
     * @param mobile      手机号码
     */
    public static void sendSMS(String templateTxt, String mobile) {
        SmsOperator smsOperator = client.getSmsOperator();
        ResultDO<SendSingleSmsInfo> resultDO = smsOperator.singleSend(mobile, templateTxt);
        logger.warn("云片sdk返回信息：", resultDO);
    }


    /**
     * 发送短信
     *
     * @param templateId 短信模板标识
     * @param mobile     手机号码
     * @param params     传入参数
     */
    public static void sendSMS(Long templateId, Map<String, Object> params, String mobile) {
        SmsOperator smsOperator = client.getSmsOperator();
        Set<String> paramSet = new HashSet<String>();
        paramSet.add("studio");//这个字段是必须的
        String templateTxt = "";
//        String templateTxt = "您在#studio#的拍摄可以选片，请访问#visit_addr#进行网上选片。";
        Assert.hasText(templateTxt, "短信模板ID【" + templateId + "】不存在");
        templateTxt = templateTxt.replaceAll("\\s*", "");
        Pattern p = compile("#\\s*(.*?)\\s*#");
        Matcher m = p.matcher(templateTxt);
        while (m.find()) {
            paramSet.add(m.group(1));
        }
        Iterator<String> iterator = paramSet.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Assert.hasText((String) params.get(key), paramSet.toString() + "参数不能为空");
            templateTxt = templateTxt.replace("#" + key + "#", (String) params.get(key));
        }
        String smsContent = "【" + params.get("studio") + "】" + templateTxt;
        ResultDO<SendSingleSmsInfo> resultDO = smsOperator.singleSend(mobile, smsContent);
        logger.debug("云片sdk返回信息：", resultDO);
    }

    public static void sendCodeSMS(String studio, String mobile, String code) {
        String smsContent = "【" + studio + "】为了确保您信息的真实性，您本次操作的验证码是" + code + "，请在页面填写验证码完成操作，验证码5分钟之内有效。";
        SmsOperator smsOperator = client.getSmsOperator();
        ResultDO<SendSingleSmsInfo> resultDO = smsOperator.singleSend(mobile, smsContent);
        logger.debug("云片sdk返回信息：", resultDO);
    }


    public static void main(String args[]) {
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("studio", "到影");
//        params.put("visit_addr", "www.baidu.com");
//        YunpianSmsUtil.sendSMS(123L, params, "15860786927");
        YunpianSmsUtil.sendSMS("【特伦新零售】尊敬的业务员，您在特伦商盟的意向用户yun(15705920288)，成功签约成为特伦云仓代理商，您可访问特伦商盟小程序查看详细信息。"
                , "15705920286");
    }
}
